using System.Net.Mail;
using System.Net;
using Microsoft.Extensions.Options;
using Models;

namespace Services
{
    /// <summary>
    /// SMTP邮件发送服务实现类
    /// </summary>
    public class SmtpEmailSender : IEmailSender
    {
        private readonly EmailSettings _emailSettings;
        private readonly ILogger<SmtpEmailSender> _logger;

        /// <summary>
        /// 构造函数，注入配置和日志服务
        /// </summary>
        public SmtpEmailSender(
            IOptions<EmailSettings> emailSettings,
            ILogger<SmtpEmailSender> logger)
        {
            _emailSettings = emailSettings.Value;
            _logger = logger;
        }

        /// <summary>
        /// 发送电子邮件
        /// </summary>
        /// <param name="email">收件人邮箱地址</param>
        /// <param name="subject">邮件主题</param>
        /// <param name="message">邮件内容</param>
        public async Task SendEmailAsync(string email, string subject, string message)
        {
            if (string.IsNullOrEmpty(email))
            {
                throw new ArgumentNullException(nameof(email));
            }

            // 配置SMTP客户端
            using var client = new SmtpClient(_emailSettings.SmtpServer, _emailSettings.SmtpPort)
            {
                EnableSsl = true,
                Credentials = new NetworkCredential(
                    _emailSettings.SmtpUsername,
                    _emailSettings.SmtpPassword)
            };

            // 创建邮件消息
            var mailMessage = new MailMessage
            {
                From = new MailAddress(_emailSettings.SenderEmail, _emailSettings.SenderName ?? "System"),
                Subject = subject,
                Body = message,
                IsBodyHtml = true
            };

            mailMessage.To.Add(new MailAddress(email));

            // 发送邮件
            await client.SendMailAsync(mailMessage);
        }
    }
} 